package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.query.StrategyDetailQuery;
import cn.wolfcode.luowowo.article.service.*;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.service.IStrategyTemplateSearchService;
import cn.wolfcode.luowowo.search.template.StrategyTemplate;
import cn.wolfcode.luowowo.search.vo.StaticVo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("strategy")
public class StrategyController {

    @Reference
    private IStrategyService strategyService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private IStrategyTagService strategyTagService;
    @Reference
    private IStrategyCommentService strategyCommentService;
    @Reference
    private IStrategyStatisRedisService strategyStatisRedisService;
    @Reference
    private IStrategyCommendService strategyCommendService;
    @Reference
    private IStrategyTemplateSearchService strategyTemplateSearchService;



    /**
     * 攻略推荐页面滑动
     * @param model
     * @return
     */
    @RequestMapping("")
    public String index(Model model,@ModelAttribute("qo")SearchQueryObject qo) {
        List<StrategyCommend> top5 = strategyCommendService.queryCommendTop5();
        model.addAttribute("commends",top5);
        //海外攻略和国内攻略
        //利用zset的排序原理
        List<StrategyStatisVO> commendList=strategyStatisRedisService.selectSort(IStrategyStatisRedisService.COMMENDS);
        //这个时候对半分,国外国内取前10
        //国外
        List<StrategyStatisVO> abroadCds=new ArrayList<>();
        //国内
        List<StrategyStatisVO> unabroadCds=new ArrayList<>();
        for (StrategyStatisVO vo : commendList) {
            if (abroadCds.size()==10&&unabroadCds.size()==10){
                break;
            }
            if (vo.isIsabroad()){
                if (abroadCds.size()<10){
                    abroadCds.add(vo);
                }
            }else {
                if (unabroadCds.size()<10){
                    unabroadCds.add(vo);
                }
            }
        }
        model.addAttribute("abroadCds",abroadCds);
        model.addAttribute("unabroadCds",unabroadCds);
        List<StrategyStatisVO> hostList=strategyStatisRedisService.selectSort(IStrategyStatisRedisService.HOTS);
        List<StrategyStatisVO> hostListTop10=null;
        if(hostList.size()>10){
           hostListTop10 = hostList.subList(0, 10);
        }else {
         hostListTop10 = hostList.subList(0, hostList.size());
        }
        model.addAttribute("hotCds",hostListTop10);
        //攻略主页的主题推荐
        List<Map<String,Object>> themeCds= null;
        List<StaticVo> chinas= null;
        List<StaticVo> abroads= null;
        List<StaticVo> themes= null;
        try {
            themeCds = strategyTemplateSearchService.selectGroupByField("themeId","themeName");
            chinas= strategyTemplateSearchService.SearchQueryGroup("provinceId","provinceName", SearchQueryObject.CONDITION_TYPE_UN_ABROAD);
            abroads= strategyTemplateSearchService.SearchQueryGroup("countryId","countryName",SearchQueryObject.CONDITION_TYPE_ABROAD);
            themes= strategyTemplateSearchService.SearchQueryGroup("themeId","themeName",SearchQueryObject.CONDITION_TYPE_THEME);
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        model.addAttribute("themeCds",themeCds);
        model.addAttribute("chinas",chinas);
        model.addAttribute("abroads",abroads);
        model.addAttribute("themes",themes);


        return "strategy/index";
    }

    @RequestMapping("/searchPage")
    public String searchPage(Model model,@ModelAttribute("qo") SearchQueryObject qo) {
        //查询游记
        Page<StrategyTemplate> page=strategyTemplateSearchService.selectStrategyByQo(qo);
        model.addAttribute("page",page);

        return "strategy/searchPageTpl";
    }

    /**
     * 游记点赞或者顶操作
     * @param sid
     * @param userInfo
     * @return
     */
    @RequestMapping("/strategyThumbup")
    @ResponseBody
    public AjaxResult strategyThumbup(Long sid,@UserParam UserInfo userInfo) {
        //首先我们调用顶的方法
        //先进行登录判断
        if(userInfo==null){
            return new AjaxResult(false,"请先进行登录喔",null,102);
        }
        //如果有登录那么调用方法
        try {
            boolean result=strategyStatisRedisService.isStrategyThumbup(sid,userInfo.getId());
            if (result){
                strategyStatisRedisService.addSortNum(RedisKeys.STRATEGY_COMMEND_SORT.getPrefix(),sid,1);
            }
            StrategyStatisVO vo=strategyStatisRedisService.getVoBystrategyId(sid);
            return new AjaxResult(result,"",vo);
        }  catch (Exception e) {
           throw new RuntimeException("收藏失败");
       }
    }
    /**
     * 收餐内容
     * @param sid 游记的ID
     * @return
     */
    @RequestMapping("/favor")
    @ResponseBody
    public AjaxResult favor(Long sid,@UserParam UserInfo userInfo) {
        //首先我们调用顶的方法
        //先进行登录判断
        if(userInfo==null){
            return new AjaxResult(false,"请先进行登录喔",null,102);
        }
       //首先我们调用收藏的方法,收藏的方法
        try {
            boolean result=strategyStatisRedisService.FavorBystrategyId(sid,userInfo);
            if (result){
                strategyStatisRedisService.addSortNum(RedisKeys.STRATEGY_COMMEND_SORT.getPrefix(),sid,1);
            }else {
                strategyStatisRedisService.addSortNum(RedisKeys.STRATEGY_COMMEND_SORT.getPrefix(),sid,-1);
            }
            StrategyStatisVO vo=strategyStatisRedisService.getVoBystrategyId(sid);
            return new AjaxResult(result,"",vo);
        } catch (Exception e) {
            throw new RuntimeException("收藏失败");
        }
    }
    /**
     * 游记页面的评论列表请求
     * @param model
     * @param qo
     * @return
     */
    @RequestMapping("/comment")
    public String comment(Model model,@ModelAttribute("qo") StrategyCommentQuery qo) {
        //去查询所有页面需要的数据.然后转到页面模板那里再返会给前端
        //查询页面所有的数据
        Page<StrategyComment> page=strategyCommentService.selectCommentForList(qo);
        model.addAttribute("page",page );
        return "strategy/commentTpl";
    }

    /**
     * 点赞用
     * @param toid
     * @param fromid
     * @return
     */
    @RequestMapping("/commentThumbUp")
    @ResponseBody
    public AjaxResult commentThumbUp(String toid,Long fromid,@UserParam UserInfo userInfo) {
       strategyCommentService.commentThumbUp(toid,userInfo.getId());
        return new AjaxResult(true,"点赞成功");
    }
    @RequestMapping("/commentAdd")
    @ResponseBody
    public AjaxResult commentAdd(@UserParam UserInfo userInfo, StrategyComment comment) {
        //首先我们保存评论,需要补全信息
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        comment.setCity(userInfo.getCity());
        comment.setLevel(userInfo.getLevel());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setCreateTime(new Date());
        //保存评论
        strategyCommentService.save(comment);
        //返回内容
        //增加文章评论内容,并且返回增加后的数量
        strategyDetailService.addReplynumByDetailId(comment.getDetailId());
        //Long count=strategyCommentService.selectCountByDetailId(comment.getDetailId());
        //还要增加评论数
        Integer replynum=null;
        try {
            replynum=strategyStatisRedisService.addStaticNum(comment.getDetailId(),1,StrategyStatisVO.STRATEGY_STATISVO_REPLYNUM).getReplynum();
        } catch (Exception e) {
         throw new RuntimeException("网络故障");
        }
        strategyStatisRedisService.addSortNum(RedisKeys.STRATEGY_HOT_SORT.getPrefix(),comment.getDetailId(),1);
        return new AjaxResult(true,"评论成功",replynum);
    }
    @RequestMapping("/detail")
    public String list(Model model, Long id,@UserParam UserInfo userInfo) {
        StrategyDetail detail = strategyDetailService.get(id);
        StrategyContent content = strategyDetailService.getContent(id);
        detail.setStrategyContent(content);
        StrategyStatisVO vo = null;
        try {
            vo = strategyStatisRedisService.addStaticNum(id,1, StrategyStatisVO.STRATEGY_STATISVO_VIEWNUM);
        } catch (Exception e) {
      throw new RuntimeException();
        }
        model.addAttribute("detail",detail);
        model.addAttribute("vo",vo);
        if (userInfo!=null){
            List<String> list = strategyStatisRedisService.getFavorListBystrateyId(id);

                model.addAttribute("isFavor",list.contains(userInfo.getId().toString()));
        }
        strategyStatisRedisService.addSortNum(RedisKeys.STRATEGY_HOT_SORT.getPrefix(),id,1);
        return "strategy/detail";
    }
    @RequestMapping("list")
    public String index(Model model, @ModelAttribute("qo") StrategyDetailQuery qo) {
        ArrayList<Destination> toasts=new ArrayList<>();
        getToasts(qo.getDestId(),toasts);
        Collections.reverse(toasts);
        toasts.remove(toasts.size()-1);
        model.addAttribute("toasts",toasts );
        //最后一个特殊处理
        Destination dest = destinationService.selecOne(qo.getDestId());
        model.addAttribute("dest",dest );
        model.addAttribute("tags",strategyTagService.list());
        //根据目的地ID和标签查询攻略列表
        model.addAttribute("pageInfo",strategyDetailService.query(qo));
        return "strategy/list";
    }
    /**
     * 内部方法用来迭代吐丝的
     * @param destinationId
     * @param toasts
     */
    private void getToasts(Long destinationId,ArrayList toasts){
        Destination destination = destinationService.selecOne(destinationId);
        toasts.add(destination);
        if (destination.getParent()!=null){
            getToasts(destination.getParent().getId(),toasts);
        }
    }
}
